<template>
  <div>
    <div class="ctl-wrapper">
      <button @click="handleDrawPoint" :class="[isDrag ? 'active' : '']">
        移动
      </button>
      <button @click="toggleDirecDraw" :class="[isDirec ? 'active' : '']">
        编辑朝向
      </button>
      <!-- <button @click="startDrawLine">画线</button> -->
    </div>
    <div>
      <el-select
        v-model="cameraIds"
        multiple
        @change="handleCameraChange"
        collapse-tags
        filterable
      >
        <el-option
          v-for="item in cameraList"
          :key="item.id"
          :label="item.id"
          :value="item.id"
        />
      </el-select>
    </div>
    <div class="status">当前状态: <span class="handle-type">就绪</span></div>
    <div ref="mapContainer" class="map-container" id="map"></div>
  </div>
</template>

<script>
import * as pdfjsLib from "pdfjs-dist/legacy/build/pdf";
import mapboxgl from "mapbox-gl";
import cameraSvg from "../../assets/camera1.svg";
import SvgSectorMarker from "./marker.js";
export default {
  data() {
    return {
      map: null,
      isDrag: false,
      isLine: false,
      cameraList: [],
      cameraSvg,
      pointList: [],
      cameraIds: [],
      defaultZoom: 10,
      defaultSize: 100,
      isDirec: true
    };
  },
  watch: {
    isDrag: {
      handler(val) {
        this.markerList.forEach(mark => {
          mark.setDraggable(val);
        });
      }
    },
    isDirec: {
      handler(val) {
        this.markerList.forEach(mark => {
          mark._this.isDirec = val;
        });
      }
    }
  },
  mounted() {
    this.initMap();
    // 初始化 PDF.js Worker
    pdfjsLib.GlobalWorkerOptions.workerSrc =
      "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.14.305/pdf.worker.min.js";
  },
  methods: {
    initMap() {
      this.getRemoteData(); // 获取远程摄像头数据
      let map = null;
      var blankStyle = {
        version: 8,
        name: "BlankMap",
        sources: {},
        layers: [
          {
            id: "background",
            type: "background",
            paint: {
              "background-color": "#fff"
            } /* 背景颜色 */
          }
        ]
      };
      mapboxgl.accessToken =
        "pk.eyJ1Ijoic2FueXJpc2luZyIsImEiOiJjbDJzaXdmMHEyYjZwM2ltdXFqYjJqc2o2In0.Gkn6qo1K_6TQiY34Pgd6Kw";
      this.map = map = new mapboxgl.Map({
        container: this.$refs.mapContainer,
        style: blankStyle,
        center: [0, 0],
        zoom: this.defaultZoom
      });

      map.on("style.load", () => {
        this.loadImage(require('./1.png'))
        // 添加自定义图层
        this.addMark(this.pointList);
        this.handleMapZoom(map);
      });
      map.on("remove", () => {
        // 地图删除触发对图纸的销毁函数
      });
    },
    loadImage(imageUrl) {
      this.map.addSource("img-layer", {
        type: "image",
        url: imageUrl,
        coordinates: [
          [-0.1, -0.1], // 左下角
          [0.1, -0.1], // 右下角
          [0.1, 0.1], // 右上角
          [-0.1, 0.1] // 左上角
        ]
      });
      this.map.addLayer({
        id: "img-overlay",
        type: "raster",
        source: "img-layer",
        paint: { "raster-opacity": 0.8 }
      });
    },
    handleCameraChange(vals) {
      vals.forEach(item => {
        // 新增的mark
        if (!this.pointList.some(i => i.id === item)) {
          let point = this.cameraList.find(i => i.id == item);
          point = {
            ...point,
            x: -0.1,
            y: 0.1
          };
          this.pointList.push(point);
          this.addMark([point]);
          this.submit();
        }
      });
      // 删除的mark
      this.pointList.forEach(item => {
        if (!vals.some(i => i == item.id)) {
          console.log("delete id", item.id);
          this.removeMark(item.id);
        }
      });
    },
    removeMark(id) {
      let index = this.pointList.findIndex(i => i.id == id);
      this.pointList.splice(index, 1);
      // 找到对应mark，删除到地图上
      let markIndex = this.markerList.findIndex(marker => {
        let element = marker.getElement();
        const markId = element.getAttribute("data-custom-id");
        if (markId == id) {
          marker.remove();
        }
        return markId == id;
      });
      this.markerList.splice(markIndex, 1);
      this.submit();
    },
    getRemoteData() {
      // 获取摄像头列表
      for (let i = 0; i < 1000; i++) {
        const point = { x: 0.05, y: 0.05, id: i };
        this.cameraList.push(point);
      }
      this.pointList = localStorage.getItem("pointList")
        ? JSON.parse(localStorage.getItem("pointList"))
        : this.pointList;
      this.cameraIds = this.pointList.map(item => item.id);
      this.featureCollection = localStorage.getItem("lineList")
        ? JSON.parse(localStorage.getItem("lineList"))
        : [];
      console.log("featureCollection", this.featureCollection);
    },
    drawCallback(e) {
      this.featureCollection = this.draw.getAll();
      this.submit();
    },
    addControlWithDraw() {
      this.map.addControl(this.draw);
      this.draw.set(this.featureCollection);
    },
    handleDrawPoint() {
      this.isDrag = !this.isDrag;
    },
    // 开启摄像头的朝向绘制
    toggleDirecDraw() {
      this.isDirec = !this.isDirec;
    },
    startDrawLine() {
      this.isDrag = false;
      this.draw.changeMode(this.draw.modes.DRAW_LINE_STRING);
    },
    addMark(pointList) {
      const diffZoom = this.map.getZoom() - this.defaultZoom;
      // 多个标记点（可拖动）
      this.markerList = this.markerList || []; //标记点集合
      // 经纬度点集合
      for (let i = 0; i < pointList.length; i++) {
        const point = pointList[i];
        const lnglat = [point.x, point.y];
        // 状态显示元素
        const statusEl = document.querySelector(".handle-type");
        const marker = new SvgSectorMarker(lnglat, {
          diffZoom,
          id: point.id,
          isDrag: this.isDrag,
          map: this.map,
          statusEl,
          isDirec: this.isDirec
        });
        // 拖拽实现旋转
        marker.on("dragend", this.onDragEnd);
        this.markerList.push(marker);
      }
    },
    handleMapZoom(map) {
      map.on("zoom", e => {
        const curZoom = e.target.getZoom();
        const diffZoom = curZoom - this.defaultZoom;
        this.markerList.map(marker => {
          marker.getElement().style.width = this.defaultSize + diffZoom * 20 + "px";
          marker.getElement().style.height = this.defaultSize + diffZoom * 20 + "px";
        });
      });
    },
    onDragEnd(e) {
      let marker = e.target;
      let lngLat = marker.getLngLat();
      let element = marker.getElement();
      const id = element.getAttribute("data-custom-id");
      const pointPos = { x: lngLat.lng, y: lngLat.lat };
      const pointData = this.pointList.find(item => item.id == id);
      console.log("marker拖动结束坐标:", pointData);
      Object.assign(pointData, pointPos);
      this.submit();
    },
    submit() {
      // 更新本地存储
      localStorage.setItem("pointList", JSON.stringify(this.pointList));
      localStorage.setItem("lineList", JSON.stringify(this.featureCollection));
    },
  }
};
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 600px;
}
.active {
  background: red;
}
</style>
<style>
@import "./marker.css";
a.mapboxgl-ctrl-logo {
  display: none !important;
}
</style>
